﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.SignalR;
using Learun.Util;
using Learun.Application.WorkFlow;
using Learun.Cache.Base;
using Learun.Cache.Factory;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Learun.Application.IM;

namespace Learun.Application.Web.Hubs
{
    public class ChatHub : Hub
    {
        private NWFProcessIBLL nWFProcessIBLL = new NWFProcessBLL();
        public ICache cache = CacheFactory.CaChe();
        private IMMsgIBLL iMMsgIBLL = new IMMsgBLL();
        public void SendMsg(string userId, string ProjectId)
        {
            if (string.IsNullOrEmpty(ProjectId))
            {
                ProjectId = "";
            }
            //获取正在连接的对象
            List<SinglaRConnect> listSinglar = cache.Read<List<SinglaRConnect>>("SinglaRConnect");
            if (listSinglar != null && listSinglar.Count > 0)
            {
                //推送给连接对象
                List<string> listConnectionId = listSinglar.Where(o => o.UserId == userId).Select(o => o.ConnectionId).ToList();
                IEnumerable<IMMsgEntity> list = new List<IMMsgEntity>();
                list = iMMsgIBLL.GetProjectMsg(ProjectId, userId);

                //获取未处理数据
                int count = 0;
                string json = "";
                list = list.OrderByDescending(x => x.F_CreateDate).ToList();
                if (list != null && list.Count() > 0)
                {
                    count = list.Count();
                    json = JsonConvert.SerializeObject(list.Take(count > 5 ? 5 : count));
                }
                ReturnData msg = new ReturnData() { Count = count, Json = json };
                GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.Clients(listConnectionId).sendMsg(msg);
            }
                
        }
        public void Send(string userId, string ProjectId)
        {
            if (string.IsNullOrEmpty(ProjectId))
            {
                ProjectId = "";
            }
            //获取正在连接的对象
            List<SinglaRConnect> listSinglar = cache.Read<List<SinglaRConnect>>("SinglaRConnect");
            if (listSinglar != null && listSinglar.Count > 0)
            {
                //推送给连接对象
                List<string> listConnectionId = listSinglar.Where(o => o.UserId == userId).Select(o => o.ConnectionId).ToList();
                string pagination = "{'rows':1000,'page':1,'sidx':'F_CreateDate DESC','sord':'ASC','records':0,'total':0}";
                string queryJson = "{ 'StartTime':'','EndTime':'','IsLook':'0'}";
                Pagination paginationobj = pagination.ToObject<Pagination>();
                IEnumerable<NWFProcessEntity> list = new List<NWFProcessEntity>();
                UserInfo userInfo = new UserInfo();
                userInfo.userId = userId;
                list = nWFProcessIBLL.GetMyMessageList(userInfo, paginationobj, queryJson, "", ProjectId);

                //获取未处理数据
                int count = 0;
                string json = "";
                list = list.OrderByDescending(x => x.F_CreateDate).ToList();
                if (list != null && list.Count() > 0)
                {
                    count = list.Count();
                    json = JsonConvert.SerializeObject(list.Take(count > 5 ? 5 : count));
                }
                ReturnData msg = new ReturnData() { Count = count, Json = json };
                GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.Clients(listConnectionId).broadcastMessage(msg);
            }
        }
        public static IEnumerable<T> IEnumerableAdd<T>(IEnumerable<T> collection, T value)
        {
            (collection as List<T>).Add(value);
            return collection;
        }
        public ReturnData sendMessage()
        {
            string pagination = "{'rows':1000,'page':1,'sidx':'F_CreateDate DESC','sord':'ASC','records':0,'total':0}";
            string queryJson = "{ 'StartTime':'','EndTime':''}";
            Pagination paginationobj = pagination.ToObject<Pagination>();
            IEnumerable<NWFProcessEntity> list = new List<NWFProcessEntity>();
            UserInfo userInfo = LoginUserInfo.Get();
            list = nWFProcessIBLL.GetMyTaskPageList(userInfo, paginationobj, queryJson, "","");
            //获取未处理数据
            int count = 0;
            string json = "";
            if (list != null && list.Count() > 0)
            {
                count = list.Count();
                json = JsonConvert.SerializeObject(list.Take(count > 5 ? 5 : count));
            }
            ReturnData msg = new ReturnData() { Count = count, Json = json };
            return msg;
        }

        /// <summary>
        /// 推送消息
        /// </summary>
        public async Task Send()
        {
            string pagination = "{'rows':1000,'page':1,'sidx':'F_CreateDate DESC','sord':'ASC','records':0,'total':0}";
            string queryJson = "{ 'StartTime':'','EndTime':''}";
            Pagination paginationobj = pagination.ToObject<Pagination>();
            IEnumerable<NWFProcessEntity> list = new List<NWFProcessEntity>();
            UserInfo userInfo = LoginUserInfo.Get();
            list = nWFProcessIBLL.GetMyTaskPageList(userInfo, paginationobj, queryJson, "","");
            //获取未处理数据
            int count = 0;
            string json = "";
            if (list != null && list.Count() > 0)
            {
                count = list.Count();
                json = JsonConvert.SerializeObject(list.Take(count > 5 ? 5 : count));
            }
            ReturnData msg = new ReturnData() { Count = count, Json = json };
            //获取正在连接的对象
            List<SinglaRConnect> listSinglar = cache.Read<List<SinglaRConnect>>("SinglaRConnect");
            if (listSinglar != null && listSinglar.Count > 0)
            {
                //推送给连接对象
                List<string> listConnectionId = listSinglar.Where(o => o.UserId == userInfo.userId).Select(o => o.ConnectionId).ToList();
                await GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.Clients(listConnectionId).SettingMessages(msg);
            }
        }

        #region 重写连接与断开方法
        /// <summary>
        /// 初连
        /// </summary>
        /// <returns></returns>
        public override Task OnConnected()
        {
            //获取参数   
            string userId = Context.Request.QueryString["userId"];
            List<SinglaRConnect> list = cache.Read<List<SinglaRConnect>>("SinglaRConnect");
            if (list == null)
            {
                list = new List<SinglaRConnect>();
            }
            list.Add(new SinglaRConnect() { UserId = userId, ConnectionId = Context.ConnectionId });
            cache.Write("SinglaRConnect", list);
            return base.OnConnected();
        }
        /// <summary>
        /// 断开
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            List<SinglaRConnect> list = cache.Read<List<SinglaRConnect>>("SinglaRConnect");
            if (list != null && list.Count > 0)
            {
                //获取参数
                string connectionId = Context.ConnectionId;
                SinglaRConnect singlar = list.Where(o => o.ConnectionId == connectionId).FirstOrDefault();
                if (singlar != null)
                {
                    list.Remove(singlar);
                }
                cache.Write("SinglaRConnect", list);
            }

            return base.OnDisconnected(stopCalled);
        }
        #endregion
    }
    /// <summary>
    /// 返回实体
    /// </summary>
    public class ReturnData
    {
        /// <summary>
        /// 未处理条数
        /// </summary>
        public int Count { get; set; }

        /// <summary>
        /// 信息集
        /// </summary>
        public string Json { get; set; }
    }
    #region SinglRConnect

    /// <summary>
    /// singlar的连接对象
    /// </summary>
    public class SinglaRConnect
    {
        public string UserId { get; set; }
        public string ConnectionId { get; set; }
    }
    #endregion
}